package com.woniuxy.redis.lock.contorller;

import cn.hutool.extra.mail.MailUtil;
import com.woniuxy.redis.lock.service.SecondService;
import com.woniuxy.redis.lock.service.SomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.MessageFormat;
import java.time.Duration;
import java.util.UUID;

/**
 * description: MyContorller <br>
 * date: 2022/1/7 5:24 下午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */
@RestController
public class MyContorller {

    @Autowired
    SomeService someService;
    @Value("${server.port}")
    int port;

    @Autowired
    SecondService secondService;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Value("${mail.subject}")
    String subject;

    @Value("${mail.content}")
    String content;
//    @RequestMapping("/some")
//    public String some() {
//        return + port + "----"+someService.some();
//    }

    @RequestMapping("/incr")
    public String incr() {
        someService.incr();
        return +port + "----" + "ok";
    }

    @RequestMapping("/start")
    public String start() {
        secondService.start();
        return +port + "----" + "初始化数据成功";
    }

    //超卖：单机、集群
    @RequestMapping("/second")
    public String second() {
        secondService.second();
        return +port + "----" + "ok";
    }

    @RequestMapping("/secondsms/{phone}")
    public String secondsms(@PathVariable("phone") String phone) {
        if (redisTemplate.hasKey(phone)) {
            return "已经发过了";
        } else {
            //产生验证码
            String code = UUID.randomUUID().toString().substring(0, 4);
            MailUtil.send("shesaifei0113@163.com", subject,
                    MessageFormat.format(content, phone, code), false);
            redisTemplate.opsForValue().set(phone, code, Duration.ofSeconds(30));
            return +port + "----" + "发送成功！";
        }

    }
}
